package com.tmac.dynamic_proxy_hook;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.tmac.library.ReflectUtils;

import java.lang.reflect.Method;

public class ProxyInstrumentation extends Instrumentation {
    Instrumentation mInstrumentation;

    public ProxyInstrumentation(Instrumentation mInstrumentation) {
        this.mInstrumentation = mInstrumentation;
    }

    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {

        // Hook之前, XXX到此一游!
        Log.d("proxy", "\n执行了startActivity, 参数如下: \n" + "who = [" + who + "], " +
                "\ncontextThread = [" + contextThread + "], \ntoken = [" + token + "], " +
                "\ntarget = [" + target + "], \nintent = [" + intent +
                "], \nrequestCode = [" + requestCode + "], \noptions = [" + options + "]");


        try {
            Class<?> aClass = Class.forName("android.app.Instrumentation");
            Method execStartActivity = ReflectUtils.getMethod(aClass, "execStartActivity",
                    Context.class, IBinder.class, IBinder.class, Activity.class,
                    Intent.class, int.class, Bundle.class);

            execStartActivity.setAccessible(true);
            return (ActivityResult) ReflectUtils.invokeMethod(execStartActivity, mInstrumentation, who,
                    contextThread, token, target, intent, requestCode, options);

        } catch (Exception e) {
            throw new RuntimeException("版本兼容");
        }

    }
}